package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageInfo;
import com.xinghai.common.constant.HttpStatus;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.page.TableDataInfo;
import com.xinghai.common.utils.DataUtil;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.SecurityUtils;
import com.xinghai.system.domain.QdOrder;
import com.xinghai.system.domain.QdPayOrderInfo;
import com.xinghai.system.domain.QdUser;
import com.xinghai.system.domain.entity.UpdateMemberInfoDTO;
import com.xinghai.system.domain.entity.UpdatePasswordDTO;
import com.xinghai.system.domain.entity.UpdateStatusDTO;
import com.xinghai.system.domain.entity.UpdateSuperDTO;
import com.xinghai.system.domain.vo.QdUserSendVO;
import com.xinghai.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员api接口
 *
 * @author xinghai
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/api/member")
public class QdMemberApiController extends BaseController
{
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdStoreService storeService;
    @Autowired
    private IQdOrderService orderService;
    @Autowired
    private IQdUserWalletService userWalletService;
    @Autowired
    private IQdPayOrderInfoService orderInfoService;


    /**
     * 查询会员详情
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(String userId)
    {
        QdUser user = userService.getById(userId);
        return success(user);
    }


    /**
     * 查询会员列表
     */
    @GetMapping("/getList")
    public AjaxResult getList(String type, Integer pageNum, Integer pageSize,String search)
    {
        QdUser user = new QdUser();
        QdUser qdUser = userService.getByLoginId(StpUtil.getLoginId(""));
        user.setSearchValue(search);
        user.setAscriptionStore(qdUser.getAscriptionStore());
        user.setStatus("0");
        if ("1".equals(type)){
            Map<String,Object> map = new HashMap<>();
            map.put("beginCreateTime", DateUtils.getBeforeWeekDate());
            map.put("endCreateTime", new Date());
            user.setParams(map);
        }else if ("2".equals(type)){
            user.setStatus("1");
        }else if ("3".equals(type)){
            user.setPowerStatus("0");
        }else if ("4".equals(type)){
            user.setPowerStatus("1");
        }
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("create_time desc");
        List<QdUser> list = userService.list(user);
        return success(getDataTable(list));
    }

    /**
     * 修改会员参数
     */
    @PostMapping("/updateInfo")
    public AjaxResult updateInfo(@Validated @RequestBody UpdateMemberInfoDTO dto)
    {
        QdUser user = new QdUser();
        //组装参数
        BeanUtils.copyProperties(dto,user);
        user.setId(dto.getUserId());
        userService.updateById(user);
        return success();
    }


    /**
     * 修改会员参数
     */
    @PostMapping("/updatePassword")
    public AjaxResult updatePassword(@Validated @RequestBody UpdatePasswordDTO dto)
    {
        QdUser user = new QdUser();
        user.setId(dto.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(dto.getPassword()));
        userService.updateById(user);
        return success();
    }


    /**
     * 修改会员邀请人
     */
    @PostMapping("/updateSuperInfo")
    public AjaxResult updateSuperInfo(@Validated @RequestBody UpdateSuperDTO dto)
    {
        return success(userService.updateSuperInfo(dto));
    }

    /**
     * 修改会员参数
     */
    @PostMapping("/updateMemberStatus")
    public AjaxResult updateMemberStatus(@Validated @RequestBody UpdateStatusDTO dto)
    {
        QdUser user = new QdUser();
        user.setId(dto.getUserId());
        user.setStatus(dto.getStatus());
        boolean b = userService.updateById(user);
        if ("1".equals(dto.getStatus())&&b){
            StpUtil.logoutByLoginId(dto.getUserId());
        }
        return success();
    }

    /**
     * 删除会员
     */
    @PostMapping("/deleteMember")
    public AjaxResult deleteMember(@Validated @RequestBody UpdateStatusDTO dto)
    {
        boolean delete = userService.delete(dto.getUserId(), true);
        if (delete){
            StpUtil.logoutByLoginId(dto.getUserId());
        }
        return success();
    }

    /**
     * 获取数据
     */
    @PostMapping("/getMemberData")
    public AjaxResult getMemberData(@Validated @RequestBody UpdateStatusDTO dto)
    {
        QdUser user = userService.getById(dto.getUserId());
        QdOrder order = new QdOrder();
        order.setBuyerUserId(user.getId());
        order.setStatus("0");
        List<QdOrder> list = orderService.list(order);
        Map<String,Object> map = new HashMap<>();
        map.put("allMoney",list.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        map.put("yyMoney",list.stream().filter(o -> ("1".equals(o.getBuyerType())||"3".equals(o.getBuyerType()))&& o.getDealTime().compareTo(DateUtils.getNowDateStart())>-1&&o.getDealTime().compareTo(DateUtils.getNowDate())<1).map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        map.put("qgMoney",list.stream().filter(o -> ("2".equals(o.getBuyerType())||"4".equals(o.getBuyerType()))&& o.getDealTime().compareTo(DateUtils.getNowDateStart())>-1&&o.getDealTime().compareTo(DateUtils.getNowDate())<1).map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));

        QdOrder order1 = new QdOrder();
        order1.setSellerUserId(user.getId());
        order1.setStatus("3");
        order1.setParams(DataUtil.getCreateTimeParams());
        List<QdOrder> list1 = orderService.list(order1);
        map.put("hbMoney",list1.stream().map(QdOrder::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        return success(map);
    }

    /**
     * 获取数据
     */
    @PostMapping("/getDealDateData")
    public AjaxResult getDealDateData(@Validated @RequestBody UpdateStatusDTO dto)
    {
        QdUser user = userService.getById(dto.getUserId());
        if (user==null){
            return error("用户不存在");
        }
        QdPayOrderInfo qdPayOrderInfo = new QdPayOrderInfo();
        qdPayOrderInfo.setUserId(user.getId());
        List<QdPayOrderInfo> list = orderInfoService.list(qdPayOrderInfo);
        List<Map<String, Object>> mapList = list.stream().map(m -> {
            Map<String, Object> map = new HashMap<>();
            map.put("date", DateUtils.dateTime(m.getCreateTime()));
            map.put("info", m.getDiff().compareTo(BigDecimal.ZERO) > 0 ? "￥" + m.getDiff().abs() : "-￥" + m.getDiff());
            return map;
        }).collect(Collectors.toList());
        return success(mapList);
    }


    /**
     * 查询发货列表
     */
    @GetMapping("/getSendList")
    public AjaxResult getSendList(String type, Integer pageNum, Integer pageSize)
    {
        QdUser user = new QdUser();
        QdUser qdUser = userService.getByLoginId(StpUtil.getLoginId(""));
        user.setAscriptionStore(qdUser.getAscriptionStore());
        user.setSendStatus(type);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("deal_day desc");
        List<QdUser> list = userService.list(user);
        List<QdUserSendVO> sendVOList = list.stream().map(m -> {
            QdUserSendVO qdUserSendVO = new QdUserSendVO();
            BeanUtils.copyProperties(m, qdUserSendVO);
            return qdUserSendVO;
        }).collect(Collectors.toList());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(sendVOList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return success(rspData);
    }


    /**
     * 发货
     */
    @PostMapping("/updateSendStatus")
    public AjaxResult updateSendStatus(@Validated @RequestBody UpdateStatusDTO dto)
    {
        QdUser user = userService.getById(dto.getUserId());
        if (user==null){
            return error("用户不存在");
        }
        if ("1".equals(user.getSendStatus())){
            return warn("用户已发货");
        }
        QdUser user1 = new QdUser();
        user1.setId(dto.getUserId());
        user1.setSendStatus("1");
        return success(userService.updateById(user1));
    }
}
